<template>
  <pageTabelLayout>
    <template #pageHeader>
      <div class="search-form divClass" v-if="headerShow" style="margin-top: 20px">
        <div>
          <a-form size="small" :model="pageData" layout="inline">
            <a-form-item label="流转卡号" label-col-flex="70px">
              <a-input
                allow-clear
                class="bacClass"
                placeholder="请扫流转卡二维码"
                v-model="pageData.flowCardCode"
                ref="getFocusSt"
                @press-enter="huiche"
                :style="{ width: '170px' }"
              />
              <!-- <a-select popup-container="html"  class="bacClass" v-model="pageData.flowCardCode" @focus="focusSel"
                                @search="handleSearch" @change="cardChange" :loading="loading" allow-clear allow-search>
                                <a-option v-for="item in pageData.cardList" :value="item.id">
                                    {{ item.flowCardCode }}
                                </a-option>
                            </a-select> -->
            </a-form-item>
            <a-form-item label-col-flex="70px" label="流转卡号">
              <a-input
                allow-clear
                :style="{ width: '170px' }"
                class="bacClass"
                placeholder=""
                v-model="pageData.flowCardCode"
                disabled
              />
            </a-form-item>
            <a-form-item label-col-flex="70px" label="布号">
              <a-input
                allow-clear
                :style="{ width: '170px' }"
                class="bacClass"
                placeholder=""
                v-model="pageData.greyCode"
                disabled
              />
            </a-form-item>
            <a-form-item label-col-flex="70px" label="品名">
              <a-input
                allow-clear
                :style="{ width: '170px' }"
                class="bacClass"
                placeholder=""
                v-model="pageData.productName"
                disabled
              />
            </a-form-item>
            <a-form-item label-col-flex="70px" label="客户名称">
              <a-input
                allow-clear
                :style="{ width: '170px' }"
                class="bacClass"
                placeholder=""
                v-model="pageData.customName"
                disabled
              />
            </a-form-item>
          </a-form>
        </div>
        <div class="my-tool-bar">
          <Toolbar
            style="float: right"
            :items="['查询', '重测', '保存']"
            @select="selectHandler"
            @saveData="saveHandler"
            @Retest="Retest"
          >
          </Toolbar>
        </div>
      </div>
      <div class="my-divisders">
        <a-divider orientation="center">
          <icon-double-up
            v-if="headerShow"
            @click="headerShow = false"
            :strokeWidth="2"
            :size="18"
          />
          <icon-double-down v-else @click="headerShow = true" :strokeWidth="2" :size="18" />
        </a-divider>
      </div>
    </template>
    <template #pageTabel>
      <a-tabs   :lazy-load="true" :justify="true" default-active-key="1" @change="handoff">
        <a-spin
          :loading="pageData.pageLoading"
          tip="加载中"
          dot
          style="height: 100%; width: 100%; z-index: 999"
        >
          <AgGridVuesCopys
            :rowHeight="33"
            :headerHeight="33"
            :suppressCopyRowsToClipboard="true"
            rowSelection="multiple"
            @grid-ready="gridReady"
            style="height: 95%"
            :localeText="localeText1"
            :defaultColDef="defaultColDef"
            class="ag-theme-alpine"
            :rowData="table.dataList"
            :columnDefs="tc"
            :suppressRowClickSelection="true"
          >
          </AgGridVuesCopys>
        </a-spin>
      </a-tabs>
    </template>
    <!-- <paginationCopys :page-size-options="pagingList1" :total="total" show-total show-jumper show-page-size
            @change="PageSize" @page-size-change="change1" style="justify-content: center;" :page-size="size"
            :current="page" /> -->
  </pageTabelLayout>
</template>
<script lang="ts">
  import { post } from '@/api/http'
  import {
    useTable,
    useRowKey,
    useTableColumn,
    usePagination,
    useRowSelection,
  } from '@/hooks/table'
  import emitter from '@/hooks/useEventBus'
  import { ref, reactive, onMounted, toRefs } from 'vue'
  import Toolbar from '@/components/Toolbar.vue'
  import { Button, Form, Message, Modal } from '@arco-design/web-vue'
  import { FormInstance } from '@arco-design/web-vue/es/form'
  import axios from 'axios'
  import filedownload from 'js-file-download'
  import usePermission from '@/store/modules/permission'
  import PageTabelLayout from '@/components/pageTabelLayout.vue'
  import MyTable from '@/components/MyTable'
  import ButtonRenderer from '@/components/TableCellRenderer/ButtonRenderer'
  import { template } from 'lodash'
  import { setupGlobalComponent } from '@/layouts'
  import { pagingList } from '@/api/paging'
  // 引入
  
  import { localeText } from '@/api/aggridZw'
  import { InputInstance } from '@arco-design/web-vue/es/input'
  import printJS from 'print-js'
  interface BrandInfo {
    id: any
    deleteState: any
  }

  export default {
    name: 'ShrinkageTest',
    setup() {
      const getFocusSt = ref<InputInstance | null>(null)
      const total = ref(0)
      const page = ref(1)
      const size = ref(10)
      const headerShow = ref<boolean>(true)
      //分页
      function PageSize(val: any) {
        page.value = val

        doRefresh()
      }
      function change1(val: any) {
        size.value = val

        doRefresh()
      }
      let id = ref(1)
      const handoff = (e: any) => {
        id.value = e
        selectHandler()
      }
      let listRow: any = ref({})
      function doRefresh() {
        if (pageData.flowCardCode.indexOf('{') != -1) {
          pageData.flowCardCode = JSON.parse(pageData.flowCardCode)['code']
        }
        if (pageData.flowCardCode == '' || pageData.flowCardCode == null) {
          Message.warning({
            content: '请先扫描流转卡号！',
            duration: 5000,
          })
          return
        }
        pageData.pageLoading = true
        post({
          url: 'pdm/WeightTest/selectKZ',
          data: {
            // "page": page.value,
            // "size": size.value,
            // greyCode: pageData.greyCode,
            flowCardCode: pageData.flowCardCode,
            // productName: pageData.productName,
            // customName: pageData.customName,
          },
        })
          .then(({ data, code, message }: any) => {
            if (code === 200) {
              listRow.value = {}
              pageData.greyCode = data[0]['greyCode']
              pageData.productName = data[0]['productName']
              pageData.customName = data[0]['customName']
              if (data[0]['xm'] == undefined || data[0]['xm'].length == 0) {
                Message.warning({
                  content: '暂无数据！',
                  duration: 5000,
                })
                return
              }
              for (let key in data[0]) {
                listRow.value[key] = data[0][key]
              }
              // listRow.value['xm'] = data[0]['xm']
              let averageMinNum = 0
              let averageMaxNum = 0
              listRow.value['xm'].forEach((o: any) => {
                if (averageMinNum == 0) {
                  averageMinNum = parseFloat(o['verifyMinNum'])
                } else {
                  averageMinNum += parseFloat(o['verifyMinNum'])
                }
                if (averageMaxNum == 0) {
                  averageMaxNum = parseFloat(o['verifyMaxNum'])
                } else {
                  averageMaxNum += parseFloat(o['verifyMaxNum'])
                }
                if (o['testResult'] == 1) {
                  o['testResult'] = '不合格'
                } else {
                  o['testResult'] = '合格'
                }
              })
              averageMinNum = averageMinNum / listRow.value['xm'].length
              averageMaxNum = averageMaxNum / listRow.value['xm'].length
              listRow.value['averageMinNum'] = averageMinNum
              listRow.value['averageMaxNum'] = averageMaxNum
              listRow.value['xm'].push({
                serialNumber: '',
                standardValue: '平均值',
                actualValue: 0,
                testResult: '',
              })
              table.handleSuccess(listRow.value['xm'])
              // total.value = data.total;
              gridOption.value.setRowData(listRow.value['xm'])
              changeHandler('')
            } else {
              Message.error({
                content: message,
                duration: 5000,
              })
            }
          })
          .catch(console.log)
          .finally(() => {
            pageData.pageLoading = false
            pageData.flowCardCode = ''
            getFocusSt.value?.focus()
          })
      }

      const pagination = usePagination(doRefresh)
      const table = useTable()

      //定型部分
      let tc: any = ref([
        {
          headerName: '次数',
          field: 'serialNumber',
          width: 150,
        },
        {
          headerName: '标准值',
          field: 'standardValue',
          width: 150,
        },
        {
          headerName: '实际值',
          field: 'actualValue',
          width: 150,
          cellRenderer: {
            template: `<a-input allow-clear :style="{ width: '200px' }" class="bacClass" placeholder="" @change="a"
                                v-model="params.data.actualValue"  />`,
            setup(props: any) {
              const a = () => {
                changeHandler(props.params.data)
              }
              return {
                a,
              }
            },
          },
        },
        {
          headerName: '测试结果',
          field: 'testResult',
          width: 150,
          cellRenderer: {
            template: `<div style="color:red" v-if='b=="不合格"'>{{b}}</div><div style="color:green" v-if='b=="合格"'>{{b}}</div>`,
            setup(props: any) {
              const a = () => {
                changeHandler(props.params.data)
              }

              return {
                a,
                b: props.params.data.testResult,
              }
            },
          },
        },
      ])

      let a = [
        {
          showRowGroup: 'hide_def',
          headerName: '',
          checkboxSelection: true,
          headerCheckboxSelection: true,
          pinned: 'left',
          width: 50,
          resizable: false,
          filter: false,
          sortable: false,
          minWidth: 50,
          maxWidth: 50,
          lockPosition: 'left',
        },
      ]
      tc.value = a.concat(tc.value)
      const dataForm = reactive<BrandInfo>({
        id: null,
        deleteState: 0,
      })
      const pageData = reactive<{
        pageLoading: boolean
        customName: any
        gdList: any[]
        nowTime: any
        checkVal: any[]
        flowCardCode: any
        greyCode: any
        productName: any
        cardList: any[]
      }>({
        pageLoading: false,
        gdList: [],
        nowTime: '',
        checkVal: [],
        flowCardCode: '',
        greyCode: '',
        productName: '',
        customName: '',
        cardList: [],
      })

      onMounted(() => {
        // 切换tap到本页面执行的方法
        // doRefresh();
        getFocusSt.value?.focus()
      })

      //查询按钮
      const selectHandler = () => {
        page.value = 1
        doRefresh()
      }

      // 表格准备事件
      const gridOption = ref()
      const gridReady = (params: any) => {
        gridOption.value = params.api
      }

      const pagingList1: any = ref(pagingList)
      const handleChange = (_data: any) => {
        table.handleSuccess(_data)
      }

      const defaultColDef = {
        sortable: true,
        resizable: true,
        filter: true,
        enableColResize: true,
      }
      //表格中文显示
      const localeText1: any = ref(localeText)

      //回车模糊查询
      const huiche = () => {
        selectHandler()
      }

      function changeHandler(data: any) {
        if (data != '') {
          if (data.actualValue < data.verifyMinNum || data.actualValue > data.verifyMaxNum) {
            data.testResult = '不合格'
          } else {
            data.testResult = '合格'
          }
        }
        let actAverage = 0
        listRow.value['xm'].forEach((o: any) => {
          if (o['actualValue'] == '' || o['actualValue'] == null) {
            o['actualValue'] = 0
          }
          if (actAverage == 0) {
            actAverage = parseFloat(o['actualValue'])
          } else {
            actAverage += parseFloat(o['actualValue'])
          }
        })
        listRow.value['xm'][listRow.value['xm'].length - 1]['actualValue'] = actAverage
        if (
          actAverage > listRow.value['averageMaxNum'] ||
          actAverage < listRow.value['averageMinNum']
        ) {
          listRow.value['xm'][listRow.value['xm'].length - 1]['testResult'] = '不合格'
        } else {
          listRow.value['xm'][listRow.value['xm'].length - 1]['testResult'] = '合格'
        }
        table.handleSuccess(listRow.value['xm'])
        gridOption.value.setRowData(listRow.value['xm'])
      }

      //根据流转卡号带出布号和重量
      const cardChange = () => {
        if (pageData.flowCardCode != null && pageData.flowCardCode != '') {
          let list = pageData.cardList.filter(function (o: any) {
            return o['flowCardCode'] == pageData.flowCardCode
          })
          if (list.length > 0) {
            pageData.greyCode = list[0]['greyCode']
            pageData.productName = list[0]['productName']
            pageData.customName = list[0]['customName']
          }
        }
      }
      //下拉框  流程卡号
      const focusSel = () => {
        selCxAll({ flowCardCode: '' })
      }
      const options = ref<any>(pageData.cardList)
      const loading = ref(false)
      const handleSearch = (value: any) => {
        if (value) {
          const ob = { flowCardCode: value }
          loading.value = true
          selCxAll(ob)
          options.value = pageData.cardList
          loading.value = false
        } else {
          options.value = []
        }
      }
      function selCxAll(val: any) {
        post({
          url: 'aps/circulatCard/getDropValue',
          data: val,
        }).then(({ data, code }: any) => {
          if (code === 200) {
            pageData.cardList = data
          } else {
          }
        })
      }
      function saveHandler() {
        listRow.value['xm'].forEach(function (o: any) {
          if (o['testResult'] == '不合格') {
            o['testResult'] = 1
          } else {
            o['testResult'] = 0
          }
        })
        post({
          url: 'pdm/WeightTest/insert',
          data: listRow.value,
        })
          .then(({ data, code, message }: any) => {
            if (code === 200) {
              Message.error({
                content: '保存成功',
                duration: 5000,
              })
              for (let key in listRow.value) {
                listRow.value[key] = ''
              }
              listRow.value.xm = []
              table.handleSuccess(listRow.value['xm'])
              gridOption.value.setRowData(listRow.value['xm'])
            } else {
              Message.error({
                content: message,
                duration: 5000,
              })
            }
          })
          .finally(() => {
            pageData.flowCardCode = ''
            getFocusSt.value?.focus()
          })
      }
      function Retest() {
        Modal.confirm({
          title: '系统提示',
          content: '确认要将实际值归零重写?',
          onOk() {
            if (listRow.value.length != 0) {
              listRow.value['xm'].forEach(function (o: any) {
                o['actualValue'] = 0
              })
              table.handleSuccess(listRow.value['xm'])
              gridOption.value.setRowData(listRow.value['xm'])
            }
          },
        })
      }
      return {
        Retest,
        saveHandler,
        loading,
        options,
        handleSearch,
        focusSel,
        cardChange,
        id,
        pagingList1,
        localeText1,
        pageData,
        dataForm,
        pagination,
        table,
        headerShow,
        total,
        page,
        size,
        tc,
        defaultColDef,
        gridOption,
        gridReady,
        huiche,
        selectHandler,
        handleChange,
        PageSize,
        change1,
        handoff,
        print,
        getFocusSt,
      }
    },
    components: { Toolbar, PageTabelLayout,  },
  }
</script>
<style scoped lang="less">
  // 表格边框线条
  :deep(.ag-cell) {
    border-right: 1px solid #dde2eb;
  }

  :deep(.ag-header-cell) {
    border-right: 1px solid #dde2eb;
  }

  :deep(.ag-cell-value) {
    user-select: initial;
    -moz-user-select: text;
    -ms-user-select: text;
    -webkit-user-select: text;
  }

  :deep(.colCss) {
    background-color: #d0ffe2;
  }

  .table tr,
  .table td span,
  .table td {
    border: 1px solid #3e3e3e;
    text-align: center;
  }
</style>
